// Copyright (c) 2022, hzmes and contributors
// For license information, please see license.txt

frappe.ui.form.on('SRM Price Compare', {
	onload: function(frm) {
		// 隐藏子表单[添加行]按钮
		frm.get_field('material_subs').grid.cannot_add_rows = true
	},

	refresh: function(frm) {
		// 隐藏删除行按钮
		$('*[data-fieldname="material_subs"]').find('.grid-remove-rows').hide();
		if (frm.doc.to_erp_price == 1) {
			// 生成ERP调价表记录
			frm.add_custom_button(__('Sync Price Adjustment'), function() {
				if(frm.doc.docstatus == 1 && frm.doc.sync == 0) {
					// 调用py方法
					frappe.call({
						method: "sync_to_price_adjustment",
						args: {session_fullname: frappe.session.user_fullname},
						doc: frm.doc,
						freeze: true,
						freeze_message: __("正在同步ERP..."),
					}).then ((r) => {
						console.log(r);
						if(r.message.length > 0) {
							// 写标识字段及ERP反馈的调价单单号
							frappe.show_alert("同步ERP成功!刷新可见ERP调价单号", 10);
							frappe.db.set_value(frm.doctype, frm.doc.name, {"sync": 1, "fbillno": r.message.join(",")})
							.then((r) => {
								frm.reload_doc();
								// frm.refresh();
							})
						}
					})
				}
				else if (frm.doc.docstatus == 0) {frappe.msgprint("未提交不允许生成ERP调价单!")}
				else if (frm.doc.sync == 1) {frappe.msgprint(`不允许重复生成ERP调价单!ERP单据:${frm.doc.fbillno}`)}
			})
		}
	}
});
